package com.freesky.provider.order.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.freesky.common.dao.entity.*;
import com.freesky.common.enums.OrderStatusEnum;
import com.freesky.common.enums.RedisKeyEnum;
import com.freesky.common.exception.EMallException;
import com.freesky.common.pojo.DataTablesResult;
import com.freesky.common.redis.IRedisTemplate;
import com.freesky.common.redis.RedisExpireTime;
import com.freesky.common.utils.IDUtil;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.common.vo.*;
import com.freesky.provider.order.config.alipay.AlipayProperties;
import com.freesky.provider.order.service.IOrderService;
import com.freesky.provider.order.util.EmailUtil;
import com.freesky.provider.order.util.OrderUtil;
import com.freesky.provider.order.util.VOUtil;
import com.freesky.provider.order.vo.VOOrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Freesky
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private IRedisTemplate redisTemplate;
    @Autowired
    private AlipayClient alipayClient;

    @Override
    public DataTablesResult getOrderList(int draw, int start, int length, String search, String orderCol, String orderDir) {

        DataTablesResult result = new DataTablesResult();
        //分页
        boolean asc = false;
        if (orderDir.equalsIgnoreCase("asc")) {
            asc = true;
        }
        Page<Order> orderPage = new Order().selectPage(new Page<>(start / length + 1, length), new EntityWrapper<Order>()
                .like("order_id", search).or()
                .like("payment", search).or()
                .like("shipping_code", search).or()
                .like("user_id", search).or()
                .like("buyer_nick", search).or()
                .like("create_time", search).or()
                .like("update_time", search).or()
                .like("payment_time", search).or()
                .like("close_time", search).or()
                .like("end_time", search).or()
                .like("status", search)
                .orderBy(orderCol, asc));

        result.setRecordsFiltered(orderPage.getTotal());
        result.setRecordsTotal(orderPage.getSize());

        result.setDraw(draw);
        result.setData(orderPage.getRecords());
        return result;
    }

    @Override
    public Long countOrder() {
        return Integer.valueOf(new Order().selectCount(new EntityWrapper())).longValue();
    }

    @Override
    public VOOrderDetail getOrderDetail(String orderId) {

        VOOrderDetail voOrderDetail = new VOOrderDetail();
        Order order = new Order(orderId);
        order = order.selectById();


        List<OrderItem> orderItemList = new OrderItem().selectList(new EntityWrapper().eq("order_id", orderId));

        OrderShipping orderShipping = new OrderShipping(orderId);
        orderShipping = orderShipping.selectById();

        voOrderDetail.setOrder(order);
        voOrderDetail.setOrderItem(orderItemList);
        voOrderDetail.setOrderShipping(orderShipping);
        return voOrderDetail;
    }

    @Override
    public JSONResponse deliver(String orderId, String shippingName, String shippingCode, BigDecimal postFee) {
        Order order = new Order(orderId);
        order = order.selectById();

        order.setShippingName(shippingName);
        order.setShippingCode(shippingCode);
        order.setPostFee(postFee);
        order.setConsignTime(new Date());
        order.setUpdateTime(new Date());
        //之前忘记设置常量了 将就这样看吧 0、未付款，1、已付款，2、未发货，3、已发货，4、交易成功，5、交易关闭
        order.setStatus(OrderStatusEnum.HAS_DELIVER.getCode());
        order.updateById();
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse remark(String orderId, String message) {
        Order o = new Order(orderId);
        o = o.selectById();
        o.setBuyerMessage(message);
        o.setUpdateTime(new Date());
        o.updateById();
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse cancelOrderByAdmin(String orderId) {

        Order o = new Order(orderId);
        o = o.selectById();
        o.setCloseTime(new Date());
        o.setUpdateTime(new Date());
        //之前忘记设置常量了 将就这样看吧 0、未付款，1、已付款，2、未发货，3、已发货，4、交易成功，5、交易关闭
        o.setStatus(5);
        o.updateById();
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public boolean deleteOrder(String id) {
        Order o = new Order(id);
        boolean delete = o.deleteById();
        if (!delete) {
            throw new EMallException("删除订单数失败");
        }

        List<OrderItem> list = new OrderItem().selectList(new EntityWrapper().eq("order_id", id));
        for (OrderItem orderItem : list) {
            boolean deleteOrderItem = orderItem.deleteById();
            if (!deleteOrderItem) {
                throw new EMallException("删除订单商品失败");
            }
        }
        OrderShipping orderShipping = new OrderShipping(id);
        boolean deleteOrderShipping = orderShipping.deleteById();
        if (!deleteOrderShipping) {
            throw new EMallException("删除物流失败");
        }
        return true;
    }

    @Override
    public int cancelOrder() {

        List<Order> list = new Order().selectAll();
        for (Order order : list) {
            judgeOrder(order);
        }
        return 1;
    }

    /**
     * 判断订单是否超时未支付
     */
    public String judgeOrder(Order order) {

        String result = null;
        if (order.getStatus() == 0) {
            //判断是否已超1天
            long diff = System.currentTimeMillis() - order.getCreateTime().getTime();
            long days = diff / (1000 * 60 * 60 * 24);
            if (days >= 1) {
                //设置失效
                order.setStatus(OrderStatusEnum.DEAL_CLOSE.getCode());
                order.setCloseTime(new Date());
                boolean update = order.updateById();
                if (!update) {
                    throw new EMallException("设置订单关闭失败");
                }
            } else {
                //返回到期时间
                long time = order.getCreateTime().getTime() + 1000 * 60 * 60 * 24;
                result = String.valueOf(time);
            }
        }
        return result;
    }

    @Override
    public int passPay(String tokenName, String token, String id) {

        //验证token
        if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(id)) {
            return -1;
        }
        String value = redisTemplate.getCacheObject(tokenName, String.class);
        if (!value.equals(token)) {
            return -1;
        }
        //展示捐赠
        Thanks thanks = new Thanks(Integer.valueOf(id));
        thanks = thanks.selectById();
        if (thanks == null) {
            return 0;
        }
        thanks.setState(1);
        boolean update = thanks.updateById();
        if (!update) {
            return 0;
        }
        //修改订单状态
        Order order = new Order(thanks.getOrderId());
        order = order.selectById();
        if (order != null) {
            order.setStatus(OrderStatusEnum.DEAL_SUCCESS.getCode());
            order.setEndTime(new Date());
            order.setUpdateTime(new Date());
            boolean updateOrder = order.updateById();
            if (!updateOrder) {
                return 0;
            }
        }
        //发送通知邮箱
        if (StringUtils.isNotBlank(thanks.getEmail()) && EmailUtil.checkEmail(thanks.getEmail())) {
            String content = "您的订单已支付成功，十分感谢您的捐赠！<br>您可以在捐赠名单中查看到您的数据：" +
                    "<a href='http://xmall.Freesky.cn/#/thanks'>http://xmall.Freesky.cn/#/thanks</a><br>Powered By XPay. Freesky Present.";
            emailUtil.sendEmailPayResult(thanks.getEmail(), "【XMall商城】支付捐赠成功通知", content);
        }
        return 1;
    }

    @Override
    public int backPay(String tokenName, String token, String id) {

        //验证token
        if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(id)) {
            return -1;
        }
        String value = redisTemplate.getCacheObject(tokenName, String.class);
        if (!value.equals(token)) {
            return -1;
        }
        //展示捐赠
        Thanks thanks = new Thanks(Integer.valueOf(id));
        thanks = thanks.selectById();
        if (thanks == null) {
            return 0;
        }
        thanks.setState(2);
        boolean update = thanks.updateById();
        if (!update) {
            return 0;
        }
        //修改订单状态
        Order order = new Order(thanks.getOrderId());
        order = order.selectById();
        if (order != null) {
            order.setStatus(OrderStatusEnum.DEAL_FAIL.getCode());
            order.setCloseTime(new Date());
            order.setUpdateTime(new Date());
            boolean updateOrder = order.updateById();
            if (!updateOrder) {
                return 0;
            }
        }
        //发送通知邮箱
        if (StringUtils.isNotBlank(thanks.getEmail()) && EmailUtil.checkEmail(thanks.getEmail())) {
            String content = "您的订单支付失败，请尝试重新支付！<br>Powered By XPay. Freesky Present.";
            emailUtil.sendEmailPayResult(thanks.getEmail(), "【EMall商城】支付失败通知", content);
        }
        return 1;
    }

    @Override
    public int notShowPay(String tokenName, String token, String id) {

        //验证token
        if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(id)) {
            return -1;
        }
//        String value=jedisClient.get(tokenName);
        String value = redisTemplate.getCacheObject(tokenName, String.class);
        if (!value.equals(token)) {
            return -1;
        }
        //展示捐赠
        Thanks thanks = new Thanks(Integer.valueOf(id));
        thanks = thanks.selectById();
        if (thanks == null) {
            return 0;
        }
        thanks.setState(3);
        boolean update = thanks.updateById();
        if (!update) {
            return 0;
        }
        //修改订单状态
        Order order = new Order(thanks.getOrderId());
        order = order.selectById();
        if (order != null) {
            order.setStatus(OrderStatusEnum.DEAL_SUCCESS.getCode());
            order.setEndTime(new Date());
            order.setUpdateTime(new Date());
            boolean updateOrder = order.updateById();
            if (!updateOrder) {
                return 0;
            }
        }
        //发送通知邮箱
        if (StringUtils.isNotBlank(thanks.getEmail()) && EmailUtil.checkEmail(thanks.getEmail())) {
            String content = "您的订单已支付成功，十分感谢您的捐赠！<br>但由于您的支付金额过低或其他原因，将不会在捐赠名单中显示，敬请谅解！" +
                    "<br>Powered By XPay. Freesky Present.";
            emailUtil.sendEmailPayResult(thanks.getEmail(), "【XMall商城】支付捐赠成功通知", content);
        }
        return 1;
    }

    @Override
    public int editPay(String tokenName, String token, Thanks thanks) {

        //验证token
        if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(thanks.getId().toString())) {
            return -1;
        }
//        String value=jedisClient.get(tokenName);
        String value = redisTemplate.getCacheObject(tokenName, String.class);
        if (!value.equals(token)) {
            return -1;
        }
        //保存
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(thanks.getTime());
            thanks.setDate(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        boolean update = thanks.updateById();
        if (!update) {
            return 0;
        }
        return 1;
    }

    @Override
    public int payDelNotNotify(String tokenName, String token, String id) {

        //验证token
        if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(id)) {
            return -1;
        }
//        String value=jedisClient.get(tokenName);
        String value = redisTemplate.getCacheObject(tokenName, String.class);
        if (!value.equals(token)) {
            return -1;
        }
        //获得捐赠
        Thanks thanks = new Thanks(Integer.valueOf(id));
        thanks = thanks.selectById();
        if (thanks == null) {
            return 0;
        }
        //删除捐赠
        boolean delete = thanks.deleteById();
        if (!delete) {
            return 0;
        }
        //修改订单状态
        Order order = new Order(thanks.getOrderId());
        order = order.selectById();
        if (order != null) {
            order.setStatus(OrderStatusEnum.DEAL_FAIL.getCode());
            order.setCloseTime(new Date());
            order.setUpdateTime(new Date());
            boolean update = order.updateById();
            if (!update) {
                return 0;
            }
        }
        return 1;
    }

    @Override
    public int payDel(String tokenName, String token, String id) {

        //验证token
        if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(id)) {
            return -1;
        }
//        String value=jedisClient.get(tokenName);
        String value = redisTemplate.getCacheObject(tokenName, String.class);
        if (!value.equals(token)) {
            return -1;
        }
        //获得捐赠
        Thanks thanks = new Thanks(Integer.valueOf(id));
        thanks = thanks.selectById();
        if (thanks == null) {
            return 0;
        }
        //删除捐赠
        boolean delete = thanks.deleteById();
        if (!delete) {
            return 0;
        }
        //修改订单状态
        Order order = new Order(thanks.getOrderId());
        if (order != null) {
            order.setStatus(OrderStatusEnum.DEAL_FAIL.getCode());
            order.setCloseTime(new Date());
            order.setUpdateTime(new Date());
            boolean update = order.updateById();
            if (!update) {
                return 0;
            }
        }
        //发送通知邮箱
        if (StringUtils.isNotBlank(thanks.getEmail()) && EmailUtil.checkEmail(thanks.getEmail())) {
            String content = "您的订单支付失败，请尝试重新支付！<br>Powered By XPay. Freesky Present.";
            emailUtil.sendEmailPayResult(thanks.getEmail(), "【EMall商城】支付失败通知", content);
        }
        return 1;
    }

    @Override
    public JSONResponse getMemberOrderList(Long userId, int page, int size) {
        //分页
        if (page <= 0) {
            page = 1;
        }
        PageHelper.startPage(page, size);

        PageOrder pageOrder = new PageOrder();
        List<VOOrder> list = new ArrayList<>();

        Page<Order> orderPage = new Order().selectPage(new Page<Order>(page, size), new EntityWrapper<Order>()
                .eq("user_id", userId)
                .orderBy("create_time", false));
        List<Order> listOrder = orderPage.getRecords();

        for (Order order : listOrder) {

            OrderUtil.judgeOrder(order);

            VOOrder voOrder = new VOOrder();
            //orderId
            voOrder.setOrderId(Long.valueOf(order.getOrderId()));
            //orderStatus
            voOrder.setOrderStatus(String.valueOf(order.getStatus()));
            //createDate
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String date = formatter.format(order.getCreateTime());
            voOrder.setCreateDate(date);
            //address
            OrderShipping orderShipping = new OrderShipping();
            orderShipping.setOrderId(order.getOrderId());
            orderShipping = orderShipping.selectById();
            VOAddress address = new VOAddress();
            address.setUserName(orderShipping.getReceiverName());
            address.setStreetName(orderShipping.getReceiverAddress());
            address.setTel(orderShipping.getReceiverPhone());
            voOrder.setAddressInfo(address);
            //orderTotal
            if (order.getPayment() == null) {
                voOrder.setOrderTotal(new BigDecimal(0));
            } else {
                voOrder.setOrderTotal(order.getPayment());
            }
            //goodsList
            List<OrderItem> listItem = new OrderItem().selectList(new EntityWrapper().eq("order_id", order.getOrderId()));

            List<CartItem> listProduct = new ArrayList<>();
            for (OrderItem orderItem : listItem) {

                CartItem cartItem = VOUtil.changeOrderItemToCartItem(orderItem);

                listProduct.add(cartItem);
            }
            voOrder.setGoodsList(listProduct);
            list.add(voOrder);
        }
        pageOrder.setTotal(getMemberOrderCount(userId));
        pageOrder.setData(list);
        return JSONResponseDiretor.buildSuccessJSONResponse(pageOrder);
    }


    @Override
    public JSONResponse getOrder(Long orderId) {

        VOOrder voOrder = new VOOrder();

        Order order = new Order();
        order.setOrderId(String.valueOf(orderId));
        order = order.selectById();
        if (order == null) {
            throw new EMallException("通过id获取订单失败");
        }

        String validTime = OrderUtil.judgeOrder(order);
        if (validTime != null) {
            voOrder.setFinishDate(validTime);
        }

        //orderId
        voOrder.setOrderId(Long.valueOf(order.getOrderId()));
        //orderStatus
        voOrder.setOrderStatus(String.valueOf(order.getStatus()));
        //createDate
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String createDate = formatter.format(order.getCreateTime());
        voOrder.setCreateDate(createDate);
        //payDate
        if (order.getPaymentTime() != null) {
            String payDate = formatter.format(order.getPaymentTime());
            voOrder.setPayDate(payDate);
        }
        //closeDate
        if (order.getCloseTime() != null) {
            String closeDate = formatter.format(order.getCloseTime());
            voOrder.setCloseDate(closeDate);
        }
        //finishDate
        if (order.getEndTime() != null && order.getStatus() == 4) {
            String finishDate = formatter.format(order.getEndTime());
            voOrder.setFinishDate(finishDate);
        }
        //address
        OrderShipping orderShipping = new OrderShipping();
        orderShipping.setOrderId(order.getOrderId());
        orderShipping = orderShipping.selectById();
        VOAddress address = new VOAddress();
        address.setUserName(orderShipping.getReceiverName());
        address.setStreetName(orderShipping.getReceiverAddress());
        address.setTel(orderShipping.getReceiverPhone());
        voOrder.setAddressInfo(address);
        //orderTotal
        if (order.getPayment() == null) {
            voOrder.setOrderTotal(new BigDecimal(0));
        } else {
            voOrder.setOrderTotal(order.getPayment());
        }
        //goodsList
        List<OrderItem> listItem = new OrderItem().selectList(new EntityWrapper().eq("order_id", order.getOrderId()));
        List<CartItem> listProduct = new ArrayList<>();
        for (OrderItem tbOrderItem : listItem) {
            CartItem VOCartProduct = VOUtil.changeOrderItemToCartItem(tbOrderItem);
            listProduct.add(VOCartProduct);
        }
        voOrder.setGoodsList(listProduct);
        return JSONResponseDiretor.buildSuccessJSONResponse(voOrder);
    }

    @Override
    public JSONResponse cancelOrder(Long orderId) {

        Order order = new Order();
        order.setOrderId(String.valueOf(orderId));
        order = order.selectById();
        if (order == null) {
            throw new EMallException("通过id获取订单失败");
        }
        order.setStatus(5);
        order.setCloseTime(new Date());
        boolean update = order.updateById();
        if (!update) {
            throw new EMallException("取消订单失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse createOrder(OrderInfo orderInfo) {
        Member member = new Member();
        member.setId(Long.valueOf(orderInfo.getUserId()));
        member = member.selectById();
        if (member == null) {
            throw new EMallException("获取下单用户失败");
        }

        Order order = new Order();
        //生成订单ID
        Long orderId = IDUtil.getRandomId();
        order.setOrderId(String.valueOf(orderId));
        order.setUserId(Long.valueOf(orderInfo.getUserId()));
        order.setBuyerNick(member.getUsername());
        order.setPayment(orderInfo.getOrderTotal());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        //0、未付款，1、已付款，2、未发货，3、已发货，4、交易成功，5、交易关闭，6、交易失败
        order.setStatus(0);
        boolean insert = order.insert();
        if (!insert) {
            throw new EMallException("生成订单失败");
        }

        List<CartItem> list = orderInfo.getGoodsList();
        for (CartItem VOCartProduct : list) {
            OrderItem orderItem = new OrderItem();
            //生成订单商品ID
            Long orderItemId = IDUtil.getRandomId();
            orderItem.setId(String.valueOf(orderItemId));
            orderItem.setItemId(String.valueOf(VOCartProduct.getProductId()));
            orderItem.setOrderId(String.valueOf(orderId));
            orderItem.setNum(Math.toIntExact(VOCartProduct.getProductNum()));
            orderItem.setPrice(VOCartProduct.getSalePrice());
            orderItem.setTitle(VOCartProduct.getProductName());
            orderItem.setPicPath(VOCartProduct.getProductImg());
            orderItem.setTotalFee(VOCartProduct.getSalePrice().multiply(BigDecimal.valueOf(VOCartProduct.getProductNum())));

            boolean insertOrderItem = orderItem.insert();
            if (!insertOrderItem) {
                throw new EMallException("生成订单商品失败");
            }

            //删除购物车中含该订单的商品
            try {
                List<CartItem> cartItemList = redisTemplate.hvals(RedisKeyEnum.MEMBER_CART_PREFIX.getKey() + ":" + orderInfo.getUserId(), CartItem.class);
                if (cartItemList != null) {
                    for (CartItem cartProduct : cartItemList) {
                        if (cartProduct.getProductId().equals(VOCartProduct.getProductId())) {
                            redisTemplate.hdel(RedisKeyEnum.MEMBER_CART_PREFIX.getKey() + ":" + orderInfo.getUserId(), cartProduct.getProductId() + "");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //物流表
        OrderShipping orderShipping = new OrderShipping();
        orderShipping.setOrderId(String.valueOf(orderId));
        orderShipping.setReceiverName(orderInfo.getUserName());
        orderShipping.setReceiverAddress(orderInfo.getStreetName());
        orderShipping.setReceiverPhone(orderInfo.getTel());
        orderShipping.setCreated(new Date());
        orderShipping.setUpdated(new Date());
        boolean insertOrderShipping = orderShipping.insert();
        if (!insertOrderShipping) {
            throw new EMallException("生成物流信息失败");
        }

        return JSONResponseDiretor.buildSuccessJSONResponse(orderId.toString());
    }

    @Override
    public JSONResponse delOrder(Long orderId) {

        Order order = new Order();
        order.setOrderId(String.valueOf(orderId));
        boolean deleteOrder = order.deleteById();
        if (!deleteOrder) {
            throw new EMallException("删除订单失败");
        }

        List<OrderItem> orderList = new OrderItem().selectList(new EntityWrapper().eq("order_id", String.valueOf(orderId)));
        for (OrderItem orderItem : orderList) {
            boolean delete = orderItem.deleteById();
            if (!delete) {
                throw new EMallException("删除订单商品失败");
            }
        }
        OrderShipping orderShipping = new OrderShipping();
        orderShipping.setOrderId(String.valueOf(orderId));
        boolean delete = orderShipping.deleteById();

        if (!delete) {
            throw new EMallException("删除物流失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse payOrder(Order order) {
//        //设置订单为已付款
//        Order order = new Order();
//        order.setOrderId(thanks.getOrderId());
//        order = order.selectById();
//        order.setStatus(1);
//        order.setUpdateTime(new Date());
//        order.setPaymentTime(new Date());
//        boolean update = order.updateById();
//        if (!update) {
//            throw new EMallException("更新订单失败");
//        }
//        //发送通知确认邮件
//        String tokenName = UUID.randomUUID().toString();
//        String token = UUID.randomUUID().toString();
//        //设置验证token键值对 tokenName:token
//        redisTemplate.putCache(tokenName, token);
//        redisTemplate.expire(tokenName, RedisExpireTime.ORDER_PAY);
//        emailUtil.sendEmailDealThank(thanks.getEmail(), "【EMall商城】支付待审核处理", tokenName, token, thanks);
//
        Order orderTemp = order.selectById();
        orderTemp.setUpdateTime(new Date());
        orderTemp.setBuyerMessage(order.getBuyerMessage());
        orderTemp.updateById();
//        //支付宝集成逻辑
        String productCode = "FAST_INSTANT_TRADE_PAY";
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(order.getOrderId());
        model.setSubject("支付测试");
        model.setTotalAmount(String.valueOf(orderTemp.getPayment()));
        model.setProductCode(productCode);

        AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();
        pagePayRequest.setReturnUrl(alipayProperties.getReturnUrl());
        pagePayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
        pagePayRequest.setBizModel(model);

        // 调用SDK生成表单, 并直接将完整的表单html输出到页面
        String form = null;
        try {
            form = alipayClient.pageExecute(pagePayRequest).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("支付宝支付异常", e);
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(form);
    }

    @Override
    public String alipayNotify() {
        String returnStr = "fail";
        String orderId = "";
        log.info("==================支付宝异步返回支付结果开始");
        //1.从支付宝回调的request域中取值
        //获取支付宝返回的参数集合
        Map<String, String[]> aliParams = this.request.getParameterMap();
        //用以存放转化后的参数集合
        Map<String, String> conversionParams = new HashMap<String, String>();
        for (Iterator<String> iter = aliParams.keySet().iterator(); iter.hasNext(); ) {
            String key = iter.next();
            String[] values = aliParams.get(key);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "uft-8");
            conversionParams.put(key, valueStr);
        }
        log.info("==================返回参数集合：" + conversionParams);
        log.info("==================支付宝异步请求逻辑处理");

        //签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        boolean signVerified = false;

        try {
            //调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(conversionParams, alipayProperties.getAlipayPublicKey()
                    , alipayProperties.getCharset(), alipayProperties.getSignType());

        } catch (AlipayApiException e) {
            log.info("==================验签失败 ！");
            e.printStackTrace();
        }

        //对验签进行处理
        if (signVerified) {
            //验签通过
            //获取需要保存的数据
            String appId = conversionParams.get("app_id");//支付宝分配给开发者的应用Id
            String notifyTime = conversionParams.get("notify_time");//通知时间:yyyy-MM-dd HH:mm:ss
            String gmtCreate = conversionParams.get("gmt_create");//交易创建时间:yyyy-MM-dd HH:mm:ss
            String gmtPayment = conversionParams.get("gmt_payment");//交易付款时间
            String gmtRefund = conversionParams.get("gmt_refund");//交易退款时间
            String gmtClose = conversionParams.get("gmt_close");//交易结束时间
            String tradeNo = conversionParams.get("trade_no");//支付宝的交易号
            orderId = tradeNo;
            String outTradeNo = conversionParams.get("out_trade_no");//获取商户之前传给支付宝的订单号（商户系统的唯一订单号）
            String outBizNo = conversionParams.get("out_biz_no");//商户业务号(商户业务ID，主要是退款通知中返回退款申请的流水号)
            String buyerLogonId = conversionParams.get("buyer_logon_id");//买家支付宝账号
            String sellerId = conversionParams.get("seller_id");//卖家支付宝用户号
            String sellerEmail = conversionParams.get("seller_email");//卖家支付宝账号
            String totalAmount = conversionParams.get("total_amount");//订单金额:本次交易支付的订单金额，单位为人民币（元）
            String receiptAmount = conversionParams.get("receipt_amount");//实收金额:商家在交易中实际收到的款项，单位为元
            String invoiceAmount = conversionParams.get("invoice_amount");//开票金额:用户在交易中支付的可开发票的金额
            String buyerPayAmount = conversionParams.get("buyer_pay_amount");//付款金额:用户在交易中支付的金额
            String tradeStatus = conversionParams.get("trade_status");// 获取交易状态

            switch (tradeStatus) // 判断交易结果
            {
                case "TRADE_FINISHED": // 交易结束并不可退款
                    returnStr = "success";
                    break;
                case "TRADE_SUCCESS": // 交易支付成功
                    returnStr = "success";
                    break;
                case "TRADE_CLOSED": // 未付款交易超时关闭或支付完成后全额退款
                    break;
                case "WAIT_BUYER_PAY": // 交易创建并等待买家付款
                    break;
                default:
                    break;
            }
        } else {
            log.info("==================支付宝官方建议校验的值（out_trade_no、total_amount、sellerId、app_id）,不一致！返回fail");
        }
        if ("success".equals(returnStr)) {
            Order order = new Order(orderId);
            order.setStatus(1);
            order.updateById();
        }
        return returnStr;
    }

    @Override
    public JSONResponse getOrderById(String orderId) {
        Order order = new Order(orderId);
        order = order.selectById();
        return JSONResponseDiretor.buildSuccessJSONResponse(order);
    }


    public int getMemberOrderCount(Long userId) {
        return new Order().selectCount(new EntityWrapper().eq("user_id", userId));
    }

}
